package com.andy.basics;

import java.io.Serializable;
import java.util.List;
import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

public class UniqueValidator implements Serializable, MessageSourceAware {

	private static final long serialVersionUID = 873412377110195920L;

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private MessageSource messageSource;

	private String model;
	private String field;

	public EntityManager getEntityManager() {
		return this.entityManager;
	}

	public void setEntityManager(final EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public String getModel() {
		return this.model;
	}

	protected void setModel(final String model) {
		this.model = model;
	}

	public String getField() {
		return this.field;
	}

	protected void setField(final String field) {
		this.field = field;
	}

	public void validate(final FacesContext context,
			final UIComponent component, final Object value)
			throws ValidatorException {
		if (this.entityManager == null) {
			FacesMessage message = new FacesMessage();
			message.setSummary("Error: "
					+ this.messageSource.getMessage("ERDB05", null,
							Locale.getDefault()));
			throw new ValidatorException(message);
		}

		List<?> list = this.entityManager.createQuery(
				"from " + this.model + " where " + this.field + "='" + value
						+ "'").getResultList();

		if (list.size() > 0) {
			FacesMessage message = new FacesMessage();
			message.setSummary(this.field + ": " + value
					+ " is already used, please use another " + this.field);
			throw new ValidatorException(message);
		}
	}

	public void setMessageSource(final MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public MessageSource getMessageSource() {
		return this.messageSource;
	}
}
